﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Cemit.NetFramework;
using Google.Protobuf;
using Google.Protobuf.Reflection;
using System.Linq;
using Cemit.PolyProto;
using UnityEditor;
using System.Reflection;

namespace Cemit.NetFramework.Demo
{
    [System.Obsolete("该DEMO已过时")]
    public class NetworkManager : MonoBehaviour
    {
        [System.Obsolete("已过时，使用帧同步框架进行案件同步")]
        public PolyPlayer playerPrefabs;
        public PolyServerSettings serverSettings;

        // Start is called before the first frame update
        void Start()
        {
            //PolyNetwork.AddMessageListener<Msg_Net_Ping>(OnMsgPing);

            PolyNetwork.OnConnectionSucceeded += OnConnected;
            PolyNetwork.OnConnectionFailed += OnDisconnected;
            PolyNetwork.Connect(serverSettings);
        }

        private void OnMsgPing(IMessage message)
        {
            Debug.Log("Ping！");
        }

        private void OnDisconnected(string obj)
        {
            Debug.LogError("连接服务器失败：" + obj);
        }

        private void OnConnected()
        {
            PolyNetwork.GetLobbyList(OnGetLoddyCallback);

            return;
            //PolyNetwork.Send(new MsgPing());
            
            //重写代码，还未写道创建角色
            //PolyNetwork.OnCreatePlayer += OnCreatePlayer;
            //PolyNetwork.OnCreatePlayerSucceeded += OnCreatePlayerSucceeded;
            //PolyNetwork.CreatePlayer(new PolyPlayerData()
            //{
            //    ID = $"御坂{Random.Range(10032, 20001)}号",
            //    position = GetRandomPosition()
            //});

            //Vector3 GetRandomPosition()
            //    => new Vector3(Random.value * 5, 1, Random.value * 5);
        }

        private void OnGetLoddyCallback(LobbyInfo[] lobbyInfo)
        {
            Debug.Log("已获取大厅列表！");
            foreach (var item in lobbyInfo)
            {
                Debug.Log($"{item.Id} {item.Name}  {item.Ip}:{item.Port}");
            }

            //PolyNetwork.JoinLobby(lobbyInfo[0]);
        }

        private void OnCreatePlayerSucceeded()
        {

            //PolyNetwork.JoinMatch(2);
        }

        [System.Obsolete("已过时，使用帧同步框架进行案件同步")]
        private void OnCreatePlayer(IPlayerData obj)
        {
            PolyPlayer player = Instantiate(playerPrefabs);
            player.playerData = (PolyPlayerData)obj;

            player.SetName(player.playerData.ID);
            player.transform.position = player.playerData.position;

            player.netInput = new PolyInput(player.playerData.ID);

            Debug.Log($"角色：{player.playerData.ID}  位置：{player.transform.position}");
        }
    }
}